#include "FileIO.h"

#include <QDebug>
#include <QFile>
#include <QDir>
#include <QQmlEngine>

FileIO::FileIO(QObject *parent) : QObject(parent)
{
}

QString FileIO::userHomePath()
{
    return qEnvironmentVariable("HOME");
}

bool FileIO::isFileExists(const QString &fileName)
{
    return QFile(fileName).exists();
}

QStringList FileIO::matchByWildcard(const QString &fileWildcard)
{
    QStringList result;

    QString fileName = fileWildcard;
    int end = 0;
    int pos = fileWildcard.indexOf('*', end);
    if (pos != -1) {
        int prev = fileWildcard.lastIndexOf('/', pos);
        int next = fileWildcard.indexOf('/', pos);
        if (prev != -1 && next != -1) {
            const QString &prefix = fileWildcard.left(prev + 1);
            const QString &mask = fileWildcard.mid(prev + 1, next - prev - 1);
            const QString &suffix = fileWildcard.right(fileWildcard.size() - next);

            QDir dir(prefix);
            const QStringList &entries = dir.entryList(QStringList() << mask,
                    QDir::Dirs | QDir::Hidden | QDir::NoDotAndDotDot);
            for (const QString &entry : entries) {
                const QString &fileName = prefix + entry + suffix;
                if (isFileExists(fileName)) {
                    result += fileName;
                }
            }
        }
    } else {
        if (isFileExists(fileName)) {
            result += fileName;
        }
    }

    return result;
}

QString FileIO::readTextFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.exists()) {
        qWarning() << "FileIO::readTextFile file doesn't exist: " + fileName;
        return QString();
    }

    if (!file.open(QFile::ReadOnly)) {
        qCritical() << "FileIO::readTextFile failed to open file for reading: " << fileName << " : " << file.errorString();
        return QString();
    }

    return QString(file.readAll());
}

bool FileIO::writeTextFile(const QString &fileName, const QString &text)
{
    QFile file(fileName);
    QDir().mkpath(QFileInfo(file).absolutePath());

    if (!file.open(QFile::ReadWrite | QFile::Truncate)) {
        qCritical() << "FileIO::readTextFile failed to open file for writing: " << fileName << " : " << file.errorString();
        return false;
    }


    qint64 res = file.write(text.toUtf8());
    if (res == -1) {
        qCritical() << "FileIO::writeTextFile failed to write to file: " << fileName << " : " << file.errorString();
        return false;
    }

    return true;
}

bool FileIO::removeFile(const QString &fileName)
{
    return QFile::remove(fileName);
}

bool FileIO::removeDirectory(const QString &path)
{
    return QDir(path).removeRecursively();
}

bool FileIO::createDirectory(const QString &path)
{
    return QDir().mkpath(path);
}

QString FileIO::localStoragePath()
{
    return qobject_cast<QQmlEngine *>(parent())->offlineStoragePath();
}
